<template>
  <div>
    <el-card class="permission-card" v-loading="loading">
      <el-form :inline="true">
        <el-form-item label-width="200px" class="per-input" size="mini">
          <el-input v-model="queryForm.title" placeholder="根据用户名搜索"></el-input>
        </el-form-item>
        <el-button size="small" @click="queryForm.title=''">清除</el-button>
        <el-button type="primary" size="small" @click="getPermissionList">搜索</el-button>
        <el-button type="success" icon="el-icon-edit" size="small" style="float:right" @click="add">新增权限</el-button>
      </el-form>

      <el-alert :title='num' type="info" show-icon :closable="false">
      </el-alert>

      <el-table ref="multipleTable" :data="PermissionList.list" tooltip-effect="dark" header-align='center'
        style="width: 100%" :default-sort="{prop: 'create_date', order: 'descending'}">
        <el-table-column type="selection" width="55">
        </el-table-column>
        <el-table-column prop="title" label="用户名" align='center'>
        </el-table-column>
        <el-table-column label="日期" sortable align='left'>
          <template v-slot={row}>
            <div>
              {{row.create_date | formatDate}}
            </div>
          </template>
        </el-table-column>

        <el-table-column align='center' label="操作" width="120">
          <template v-slot='{row}'>
            <el-button type="primary" icon="el-icon-edit" circle size="small" @click="edit(row)" plain></el-button>
            <el-button type="danger" @click="del(row)" icon="el-icon-delete" circle size="small" plain></el-button>
          </template>
        </el-table-column>

      </el-table>
      <!-- 分页 -->
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryForm.page" :page-sizes="[1,5,10]" :total="llength" :page-size="queryForm.pagesize"
        layout="  sizes, prev, pager, next, jumper">
      </el-pagination>
    </el-card>

    <el-dialog title="创建权限组" :visible.sync="addVisible" width="840px" :before-close="addhandleClose">
      <el-form class="addform" ref='userAddData' @submit.native.prevent :rules="addFromRules" :model='addinfo'>
        <div>
          <el-form-item label="用户名" :lable='addinfo.title' label-width='120px' class="addinput" prop="title">
            <el-input v-model="addinfo.title"></el-input>
          </el-form-item>
          <el-form-item label="权限分配" label-width='120px' class="addinput" prop='permissions'>
            <el-tree :data="MenuList" show-checkbox node-key="id" ref="tree" highlight-current
              :default-expanded-keys="[0]" :props='treeProps' :default-expand-all='false' @check='currentaddChecked'>
            </el-tree>
          </el-form-item>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addVisible = false">取 消</el-button>
        <el-button type="primary" @click="addsubmit">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="编辑权限组" :visible.sync="editVisible" width="840px" :before-close="edithandleClose">
      <el-form class="addform" ref='userEditData' @submit.native.prevent :rules="editFromRules" :model='editinfo'>
        <div>
          <el-form-item label="用户名" :lable='editinfo.title' label-width='120px' class="addinput" prop="title">
            <el-input v-model="editinfo.title"></el-input>
          </el-form-item>
          <el-form-item label="权限分配" label-width='120px' class="addinput" prop='permissions'>
            <el-tree :data="MenuList" show-checkbox node-key="id" ref="tree" highlight-current
              :default-expanded-keys="[0]" :default-checked-keys="editinfo.permissions" :props='treeProps'
              :default-expand-all='false' @check='currentChecked'>
            </el-tree>
          </el-form-item>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitedit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { list1, detail1, update1, remove1, add1 } from '../../api/base/permissions.js'
import { parseTime } from '../../filters/index.js'
import { list } from '../../api/base/menus.js'
import { formatTime } from '../../utils/index.js'

export default {
  data () {
    return {
      addinfo: {
        id: null,
        title: '',
        permissions: []
      },
      addVisible: false,
      addFromRules: {
        title: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        permissions: [
          { type: 'array', required: true, message: '请至少选择一个活动性质', trigger: 'change' }
        ]
      },
      editFromRules: {
        title: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        permissions: [
          { type: 'array', required: true, message: '请至少选择一个活动性质', trigger: 'change' }
        ]
      },
      currentlist: [],
      editinfo: {
        id: null,
        title: '',
        permissions: []
      },
      treeProps: {
        children: 'points',
        label: 'title'
      },
      menuList: [],
      MenuList: {
      },
      editVisible: false,
      queryForm: {
        title: '',
        page: 1,
        pagesize: 5
      },
      llength: 0,
      loading: true,
      PermissionList: []
    }
  },
  computed: {
    fomat () {
      return formatTime(Date)
    },
    num () {
      return ('共' + this.llength + '条数据')
    }
  },
  filters: {
    formatDate: function (time) {
      if (time != null && time !== '') {
        var date = new Date(time)
        console.log(date)
        return parseTime(date)
      } else {
        return ''
      }
    }
  },
  created () {
    this.getPermissionList()
    this.getMenuList()
  },

  methods: {
    addhandleClose () {

    },
    currentaddChecked (nodeObj, SelectedObj) {
      this.addinfo.permissions = SelectedObj.checkedKeys
    },
    add () {
      this.addVisible = true

      //  this.addinfo.permissions = []
    },
    addsubmit () {
      this.$refs.userAddData.validate(async bool => {
        if (!bool) return this.$message.error('不能为空')
        const { data: res } = await add1(this.addinfo)

        this.$message.success('提交成功')
        this.addVisible = false
        if (res) {
          this.addinfo.title = ''

          this.addinfo.permissions.forEach(item => {
            this.$refs.tree.setChecked(item, false, true)
          })
          //     this.$nextTick(() => {
          //    this.$refs.tree.setChecked([],false)
          // })
          // this.addinfo.permissions = []
          this.addinfo.id = null
        }
      })
      // 关闭对话框

      // 重新获取最新数据
      this.getPermissionList()
    },
    currentChecked (nodeObj, SelectedObj) {
      this.editinfo.permissions = SelectedObj.checkedKeys
      console.log(this.editinfo.permissions)
    },
    submitedit () {
      this.$refs.userEditData.validate(async bool => {
        if (!bool) return this.$message.error('不能为空')
        const { data: res } = await update1(this.editinfo)
        console.log(res)
        this.$message.success('修改成功')
        this.editVisible = false
      })
      // 关闭对话框

      // 重新获取最新数据
      this.getPermissionList()
    },
    async getMenuList () {
      const { data: res } = await list()
      if (res.length !== 0) {
        this.menuList = res
      }
      const newMenuList = JSON.parse(JSON.stringify(this.menuList))
      // 修改返回值key
      var keyMap = {
        childs: 'points'
      }
      for (var i of newMenuList) {
        for (var j in i) {
          var newKey = keyMap[j]
          if (newKey) {
            i[newKey] = i[j]
            delete i[j]
          }
        }
      }
      var arr = {}
      var arr1 = []
      arr.points = newMenuList
      arr.id = 0
      arr.pid = null
      arr.title = '系统菜单和页面权限点'
      arr.code = ''

      arr1.push(arr)
      console.log(newMenuList)

      this.MenuList = arr1
      console.log(this.MenuList)
    },
    edithandleClose () {
      this.editVisible = false
    },
    async edit (row) {
      this.editVisible = true
      this.editinfo.title = row.title
      this.editinfo.id = row.id
      const { data: res } = await detail1(row)
      this.editinfo.permissions = res.permissions
    },
    handleSizeChange (val) {
      this.queryForm.pagesize = val
      this.getPermissionList()
    },
    handleCurrentChange (val) {
      this.queryForm.page = val
      this.getPermissionList()
    },
    async getPermissionList () {
      const { data: res } = await list1(this.queryForm)
      if (res.length !== 0) {
        this.PermissionList = res
        this.loading = false
      }

      this.llength = this.PermissionList.counts
    },
    async del (row) {
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消删除')
      }
      await remove1(row)
      this.getPermissionList()
      this.$message.success('成功')
    }
  }
}
</script>

<style scoped lang='less'>
/deep/ .permission-card {
  margin: 20px 20px;
}
/deep/ .per-input {
  height: 32px;
}
.el-alert {
  margin-bottom: 20px;
}
.el-alert__title/deep/.el-alert__closebtn .el-icon-close::before {
  display: none;
}
.el-pagination {
  margin-top: 10px;
  float: right;
  margin-bottom: 10px;
}
.addform {
  width: 400px;
  margin-left: 120px;
}
.addinput {
  margin-left: -40px;
}
</style>
